import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Divider, Table, Input, Button, Space, Modal, Form, Select, DatePicker, message } from 'antd';
import type { PaginationProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import './vipList.less'
import { getVipApi, deleteVipApi, updateVipApi, searchVipApi } from '@/api/vip/vip'
import VipData from '@/components/VipData';
import useStore from '@/store/index'

const { Option } = Select;
const { Search } = Input;
interface DataType {
  key: React.ReactNode;
  name: string;
  age: number;
  address: string;
  children?: DataType[];
}

interface DataNodeType {
  value: string;
  label: string;
  children?: DataNodeType[];
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 16,
    },
  },
};
const VipList: React.FC = () => {
  useEffect(() => {
    getVipList(pageSize, pageNum)
  }, []);
  const NavigateTo = useNavigate()
  const userInfo = useStore<any>((state: any) => state.userInfo)
  const [viplist, setviplist] = useState<any>();
  const [pageNum, setPageNum] = useState<any>(1);
  const [pageSize, setPageSize] = useState<any>(10);
  const [total, setTotal] = useState<any>(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 表格内容
  const [form] = Form.useForm();
  const [updateData, setUpdateData] = useState<any>()
  const [selectKeys, setSelectedKeys] = useState<any[]>([]);
  // 批量操作id
  const [idArr, setIdArr] = useState<any>()
  // ui结构
  const columns: ColumnsType<DataType> = [
    {
      title: '姓名',
      width: 100,
      dataIndex: 'vipName',
      key: '1',
      fixed: 'left',
    },
    {
      title: '姓名',
      width: 100,
      dataIndex: 'sex',
      key: '2',
    },
    {
      title: '会员号',
      width: 100,
      dataIndex: 'id',
      key: '3',
    },
    {
      title: '会员等级',
      width: 100,
      dataIndex: 'vipRank',
      key: '4',
    },
    {
      title: '手机号',
      dataIndex: 'vipPhone',
      key: '5',
      width: 150,
    },
    {
      title: '余额',
      dataIndex: 'money',
      key: '6',
      width: 150,
    },
    {
      title: '积分',
      dataIndex: 'score',
      key: '7',
      width: 150,
    },
    {
      title: '已消费',
      dataIndex: 'consumed',
      key: '8',
      width: 150,
    },
    {
      title: '开卡日期',
      dataIndex: 'openTime',
      key: '9',
      width: 150,
    },
    {
      title: '到期时间',
      dataIndex: 'expires',
      key: '10',
      width: 150,
    },
    {
      title: '开卡人',
      dataIndex: 'openStaff',
      key: '11',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: '12',
      width: 150,
    },
    {
      title: '操作',
      key: '13',
      fixed: 'right',
      width: 170,
      render: (record) => <div className='operate'>
        <Button type="primary" style={{marginRight:'10px'}} onClick={() => showModal(record)}>修改</Button>
        <Button type={'primary'} style={{ backgroundColor: record.status == '正常' ? '#E61A42' : '#4c925d' }} onClick={() => {
          deleteVip(record)
        }}>{record.status == '正常' ? '禁用' : '启用'}</Button>
      </div>,

    },

  ];
  // 性别选项
  const sex = (
    <Form.Item name="sex" noStyle>
      <Select style={{ width: 70 }}>
        <Option value="男士">男士</Option>
        <Option value="女士">女士</Option>
        <Option value="保密">保密</Option>
      </Select>
    </Form.Item>
  );
  const vipRank = (
    <Form.Item name="vipRank" noStyle>
      <Select style={{ width: 100 }}>
        <Option value="黄金会员">黄金会员</Option>
        <Option value="铂金会员">铂金会员</Option>
        <Option value="砖石会员">砖石会员</Option>
      </Select>
    </Form.Item>
  );
  const status = (
    <Form.Item name="status" noStyle>
      <Select style={{ width: 100 }}>
        <Option value="正常">正常</Option>
        <Option value="禁用">禁用</Option>
      </Select>
    </Form.Item>
  );

  // 方法函数
  useEffect(() => {

  }, [updateData]);
  const onFinish = (values: any) => {
    // console.log('Received values of form: ', values);
    let updateVipParams = {
      id: values.id,
      vipName: values.vipName,
      sex: values.sex,
      vipPhone: values.vipPhone,
      expires: values.expires.format('YYYY-MM-DD'),
      vipRank: values.vipRank,
      money: values.money,
      score: values.score,
      openStaff: values.openStaff,
      status: values.status == '正常' ? '0' : '1',
    }
    try {
      updateVipApi(updateVipParams).then(updateVipRes => {
        if (updateVipRes.code == 200) {
          message.open({
            type: 'success',
            content: updateVipRes.msg,
          });
          setIsModalOpen(false);
          getVipList(pageSize, pageNum)
        } else {
          message.open({
            type: 'error',
            content: updateVipRes.msg,
          });
        }
      })
    } catch (error) {
      message.open({
        type: 'error',
        content: '修改失败' + error,
      });
    }
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const showModal: any = (record: any) => {
    let vipInfo: any = {
      id: record.key,
      vipName: record.vipName,
      sex: record.sex,
      vipPhone: record.vipPhone,
      vipRank: record.vipRank,
      money: record.money,
      score: record.score,
      openStaff: record.openStaff,
      oldExpires: record.expires,
      expires: dayjs(record.expires),
      status: record.status,
    }
    form.setFieldsValue(vipInfo)
    setIsModalOpen(true);
  };

  const deleteVip: any = (record: any) => {
    let id = { id: record.key, status: record.status == '正常' ? 0 : 1 }
    deleteVipApi(id).then(deleteVipRes => {
      message.open({
        type: 'success',
        content: deleteVipRes.msg,
      });
      getVipList(pageSize, pageNum)
    })
  }
  //  获取会员信息的方法
  const getVipList: any = (pageSize: any, pageNum: any) => {
    let params = { pageSize: pageSize, pageNum: pageNum, belongToShop: userInfo.storeId }
    getVipApi(params).then(getVipRes => {
      setTotal(getVipRes.total)
      let newVipList = getVipRes.viplist.map((viplist_item) => {
        return {
          "id": viplist_item.id.substring(0, 6),
          'key': viplist_item.id,
          "vipName": viplist_item.vipName,
          "sex": viplist_item.sex,
          "vipPhone": viplist_item.vipPhone,
          "openTime": viplist_item.openTime.substring(0, 10),
          "expires": viplist_item.expires.substring(0, 10),
          "vipRank": viplist_item.vipRank,
          "consumed": viplist_item.consumed,
          "money": viplist_item.money,
          "score": viplist_item.score,
          "openStaff": viplist_item.openStaff,
          "status": viplist_item.status == 0 ? '正常' : "禁用",
        }
      })
      setviplist(newVipList)
    })
  }
  //  页码改变触发
  const pageNumChange: PaginationProps['onChange'] = (page) => {
    setPageNum(page);
    getVipList(pageSize, page)
  };
  // 搜索事件
  const onSearch: any = (value: string) => {
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    searchVipApi(params).then(searchRes => {
      if (searchRes.code == 200) {
        let newVipList = searchRes.viplist.map((viplist_item) => {
          return {
            "id": viplist_item.id.substring(0, 6),
            'key': viplist_item.id,
            "vipName": viplist_item.vipName,
            "sex": viplist_item.sex,
            "vipPhone": viplist_item.vipPhone,
            "openTime": viplist_item.openTime.substring(0, 10),
            "expires": viplist_item.expires.substring(0, 10),
            "vipRank": viplist_item.vipRank,
            "consumed": viplist_item.consumed,
            "money": viplist_item.money,
            "score": viplist_item.score,
            "openStaff": viplist_item.openStaff,
            "status": viplist_item.status == 0 ? '正常' : "禁用"
          }
        })
        setviplist(newVipList)
        message.open({
          type: 'success',
          content: searchRes.msg,
        });
      } else {
        message.open({
          type: 'error',
          content: searchRes.msg,
        });
      }
    })
  }
  // 刷新列表
  const onRefresh: any = () => {
    try {
      getVipList(pageSize, pageNum)
      message.open({
        type: 'success',
        content: '刷新成功',
      });
    } catch (error) {
      message.open({
        type: 'error',
        content: '刷新失败' + error,
      });
    }
  }
  // 添加会员
  const goAddVip: any = () => {
    NavigateTo('/vipcsm/addvip')
  }
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys: selectKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedKeys(selectedRowKeys)
      // console.log('选择改变');
      // console.log(`selectedRowKeys: ${selectedRowKeys}`);
      // console.log('selectedRows: ', selectedRows);
      let id = selectedRows.map((item: any) => {
        return item.key
      })
      setIdArr(id)
    },
    onSelect: (record, selected, selectedRows) => {
      // console.log('选择');
      // console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      // console.log('选择全部');

      // console.log(selected, selectedRows, changeRows);
    },

  }
  const goStart: any = () => {
    let params = { id: idArr, status: 1 }
    deleteVipApi(params).then(deleteVipRes => {
      setSelectedKeys([])
      message.open({
        type: 'success',
        content: deleteVipRes.msg,
      });
      getVipList(pageSize, pageNum)
    })
  }
  const goBan: any = () => {
    let params = { id: idArr, status: 0 }
    deleteVipApi(params).then(deleteVipRes => {
      setSelectedKeys([])
      message.open({
        type: 'success',
        content: deleteVipRes.msg,
      });
      getVipList(pageSize, pageNum)
    })
  }
  return (
    <div >
      <div>
        <div>
          <Search
            placeholder="手机号/会员卡号/姓名"
            allowClear
            enterButton="搜索"
            // style={{ width: 304 }}
            onSearch={onSearch}
            style={{ width: 300 }}
          />
          <Button className='vip_btn' type="primary" onClick={goAddVip}>
            添加会员
          </Button>
          <Button className='vip_btn' onClick={goStart} type="primary">
            批量启用
          </Button>
          <Button className='vip_btn' onClick={goBan} type="primary">
            批量禁用
          </Button>
          <Button className='vip_btn' onClick={onRefresh} type="primary" shape="circle" icon={<ReloadOutlined />} />
        </div>

      </div>

      <Modal footer={null} title='修改用户信息' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>

        <Form
          form={form}
          name="register"
          onFinish={onFinish}
          style={{ maxWidth: 600 }}
          scrollToFirstError
          initialValues={{ vipName: '' }}

        >
          <Form.Item
            name="id"
            label="卡号"
            rules={[
              {
                required: true,
                message: '请输入卡号',
              },
            ]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            name="vipName"
            label="姓名"
            rules={[
              {
                required: true,
                message: '请输入姓名',
              },
            ]}
          >
            <Input addonAfter={sex} />
          </Form.Item>
          <Form.Item
            name="vipPhone"
            label="手机号"
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="vipRank"
            label="会员等级"
            rules={[
              {
                required: true,
                message: '请输入会员等级',
              },
            ]}
          >
            <Input disabled={true} addonAfter={vipRank} />
          </Form.Item>
          <Form.Item
            name="money"
            label="余额"
            rules={[
              {
                required: true,
                message: '请输入余额',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="score"
            label="积分"
            rules={[
              {
                required: true,
                message: '请输入积分',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="oldExpires"
            label="原本到期时间"
            rules={[
              {
                required: true,
                message: '请输入原本到期时间',
              },
            ]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item name="expires" label="到期时间" rules={[
            {
              required: true,
              message: '请输入日期',
            },
          ]} >
            <DatePicker style={{ width: 200 }}></DatePicker>
          </Form.Item>
          <Form.Item
            name="openStaff"
            label="开卡员工"
            rules={[
              {
                required: true,
                message: '请输入开卡员工',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[
              {
                required: true,
                message: '请输入开卡员工',
              },
            ]}
          >
            <Input disabled={true} addonAfter={status} />
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button onClick={handleOk} style={{ marginRight: 20 }}>取消</Button>
            <Button type="primary" htmlType="submit">
              修改
            </Button>
          </Form.Item>

        </Form>
      </Modal>
      <VipData></VipData>
      <Space align="center" style={{ marginBottom: 16 }}>
      </Space>

      <Divider />
      <Table columns={columns} dataSource={viplist} scroll={{ x: 1500, y: 300 }}
        rowSelection={{ ...rowSelection }}
        pagination={{
          pageSize: pageSize,
          defaultCurrent: pageNum,
          total: total,
          onChange: pageNumChange,
        }} />
    </div>
  );
};

export default VipList;